﻿function SPListManager(siteUrl, listTitle, xmlCamlQuery, viewFields, folderServerRelativeUrl, datesInUtc) {

    if (isHostDataRequest) {
        this.SiteUrl = $("#txtSPAppWebUrl").val();
    }
    else {
        this.SiteUrl = siteUrl;
    }
    this.ListTitle = listTitle;
    this.XmlCamlQuery = xmlCamlQuery;
    this.ViewFields = viewFields;
    this.FolderServerRelativeUrl = folderServerRelativeUrl;
    this.DatesInUtc = datesInUtc;
    this.collListItem = null;

    this.Execute = function () {
        console.log("Started...");
        console.log(this.SiteUrl);

        var deferred = $.Deferred();

        var clientContext = new SP.ClientContext(this.SiteUrl);
        var oList = null;
        if (isHostDataRequest) {
            var appContextSite = new SP.AppContextSite(clientContext, $("#txtSPHostUrl").val());
            oList = appContextSite.get_web().get_lists().getByTitle(this.ListTitle);
        }
        else {
            oList = clientContext.get_web().get_lists().getByTitle(this.ListTitle);
        }

        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml(this.XmlCamlQuery);

        if (this.FolderServerRelativeUrl && this.FolderServerRelativeUrl !== "") {
            camlQuery.set_folderServerRelativeUrl(this.FolderServerRelativeUrl);
        }

        camlQuery.set_datesInUtc(this.DatesInUtc);

        this.collListItem = oList.getItems(camlQuery);

        var includeFields = JoinViewFieldsByComma(this.ViewFields);
        console.log(includeFields);
        clientContext.load(this.collListItem, "Include(" + includeFields + ")");

        //clientContext.executeQueryAsync(Function.createDelegate(this, this.Success), Function.createDelegate(this, this.Fail));

        clientContext.executeQueryAsync(
            Function.createDelegate(this,
                function () {
                    deferred.resolve(this);
                    console.log("Resolve");
                }),
            Function.createDelegate(this,
                function (sender, args) {
                    deferred.reject(sender, args);
                    console.log("Reject");
                }));

        console.log("Completed...");

        return deferred.promise();
    };

    //this.Execute = function () {
    //    console.log(this.SiteUrl);
    //    console.log(this.ListTitle);
    //    this.SPRequest().then(
    //        Function.createDelegate(this, this.Success),
    //        Function.createDelegate(this, this.Fail)
    //    );
    //};

    this.Success = function (sender, args) {

        var listItemInfo = '';
        var jsonRows = "";
        var resultColumns = [];

        var listItemEnumerator = this.collListItem.getEnumerator();

        while (listItemEnumerator.moveNext()) {
            var jsonRow = "{";

            var jsonPropertyKeyValue = "";

            var oListItem = listItemEnumerator.get_current();
            var fieldValuesObj = oListItem.get_fieldValues();

            for (var index in this.ViewFields) {

                var internalName = this.ViewFields[index][0];

                if (jQuery.inArray(internalName, resultColumns) === -1) {
                    resultColumns.push(internalName);
                }

                var fieldType = this.ViewFields[index][1];
                // DO NOT DELETE
                //var jsonPropertyValue = oListItem.get_item(internalName);
                var jsonPropertyValue = fieldValuesObj[internalName];

                if (jsonPropertyValue) {
                    if (IsLookupType(fieldType) || fieldType === "User") {
                        if ($.isArray(jsonPropertyValue) === true) {
                            var tempValue = "";
                            $.each(jsonPropertyValue, function (index, value) {
                                if (index > 0) {
                                    tempValue += ";";
                                }
                                tempValue += value.get_lookupValue();
                            });

                            jsonPropertyValue = tempValue;
                        }
                        else if (jQuery.type(jsonPropertyValue) === "string") {
                            jsonPropertyValue = jsonPropertyValue;
                        }
                        else {
                            if (typeof jsonPropertyValue.get_lookupValue === 'function') {
                                jsonPropertyValue = jsonPropertyValue.get_lookupValue();
                            }
                            else if (typeof jsonPropertyValue.toString === 'function') {
                                jsonPropertyValue = jsonPropertyValue.toString();
                            }
                        }
                    }
                } else {
                    jsonPropertyValue = "";
                }

                if (jsonPropertyKeyValue.length > 0) {
                    jsonPropertyKeyValue += ",";
                }

                jsonPropertyKeyValue += "\"" + internalName + "\" : " + "\"" + EncodeJasonValue(jsonPropertyValue) + "\"";
            }

            if (jsonRows.length > 0) {
                jsonRows += ",";
            }

            jsonRows += "{" + jsonPropertyKeyValue + "}";
        }

        jsonRows += "";

        var tempJsonData = JSON.parse("[" + jsonRows + "]");

        //console.log(listItemInfo);

        LoadJsonDataToGrid(resultColumns, tempJsonData, "tabCamlResultDiv", "bootGridCamResultDiv");
        console.log("Success...");
    }

    this.Fail = function (sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
}